/*
 * @Author: zi.yang
 * @Date: 2021-10-02 13:39:17
 * @LastEditors: zi.yang
 * @LastEditTime: 2021-10-09 08:50:38
 * @Description: In User Settings Edit
 * @FilePath: \one.pm\src\store\User\actions.js
 */
import request from '@/apis'

export default {
  // 用户登录
  FetchLogin: ({ commit }, data) => {
    return new Promise((resolve, reject) => {
      request
        .fetchLogin(data)
        .then((res) => {
          commit('SET_TOKEN', res.data.token)
          commit('SET_USER_INFO', res.data.sysUser)
          commit('SET_LOGIN_TIME', res.data.loginTime)
          return resolve(res)
        })
        .catch((err) => reject(err))
    })
  },
  // 刷新token
  FetchRefreshToken: ({ commit, getters }) => {
    return new Promise((resolve, reject) => {
      const { username, password } = getters.userinfoState
      request
        .fetchRefreshToken({ username, password }, getters.loginTimeState)
        .then((res) => {
          commit('SET_TOKEN', res.data.token)
          commit('SET_LOGIN_TIME', res.data.loginTime)
          return resolve(res)
        })
        .catch((err) => reject(err))
    })
  },
  // 获取用户列表
  FetchFindAllUser: ({ commit, rootGetters }) => {
    return new Promise((resolve, reject) => {
      request
        .fetchFindAllUser()
        .then((res) => {
          const dataMap = res.data.map((row) => {
            const status = rootGetters['Dict/userStatusState'].find(dict => dict.dictValue === row.status)
            row.status = status.dictLabel
            return row
          })
          commit('SET_USER_LIST', dataMap)
          return resolve(dataMap)
        })
        .catch((err) => reject(err))
    })
  },
  // 删除一个用户
  FetchUserDelete: ({ commit }, id) => {
    return new Promise((resolve, reject) => {
      request.fetchUserDelete(id)
        .then(res => {
          commit('DEL_USER_IN_LIST', id)
          return resolve(res)
        }).catch(err => reject(err))
    })
  }
}
